const $inputUserName = $('.user-name-input'); // 输入用户名
const $inputPassword = $('.password-input'); // 输入密码
const $clearUserNameBtn = $('.clear-user-name'); // 清除用户名按钮
const $clearPasswordBtn = $('.clear-password'); // 清除密码按钮
const $showPasswordBtn = $('.show-password');  // 显示密码按钮
const $hidePasswordBtn = $('.hide-password');  // 隐藏密码按钮
const $loginBtn = $('.btn');  // 登录按钮

let userName = '';  // 用户名
let password = '';  // 密码
let loginClientId;  // loginClientId
let loginToken;  // loginToken

// 用户名输入
$inputUserName.on('input', (event) => {
  const value = event.target.value;
  userName = value;
  if(value.length > 0) {
    $clearUserNameBtn.show();
  } else {
    $clearUserNameBtn.hide();
  }
  $inputUserName.removeClass('is-active');
});

// 清空用户名
$clearUserNameBtn.on('click', () => {
  userName = '';
  $inputUserName.val('');
  $clearUserNameBtn.hide();
});

// 密码输入
$inputPassword.on('input', (event) => {
  const value = event.target.value;
  password = value;
  if(value.length > 0) {
    $clearPasswordBtn.show();
  } else {
    $clearPasswordBtn.hide();
  }
  $inputPassword.removeClass('is-active');
});

// 清空密码
$clearPasswordBtn.on('click', () => {
  password = '';
  $inputPassword.val('');
  $clearPasswordBtn.hide();
});

// 显示密码
$showPasswordBtn.on('click', () => {
  $inputPassword.attr('type', 'text');
  $showPasswordBtn.hide();
  $hidePasswordBtn.show();
});

// 隐藏密码
$hidePasswordBtn.on('click', () => {
  $inputPassword.attr('type', 'password');
  $hidePasswordBtn.hide();
  $showPasswordBtn.show();
});

// 获取页面的ClientId和token
$.ajax({
  method: 'GET',
  url: 'https://account.teambition.com/login',
  success(data) {
    const htmlArr = data.split('<script');
    const parameArr = htmlArr[2].split('"');
    loginClientId = parameArr[3];
    loginToken = parameArr[5];
  },
});

// 登录
$loginBtn.on('click', () => {
  if ((userName === '') || (password === '')) {
    if(userName === '') {
      $inputUserName.addClass('is-active');
    } else {
      $inputUserName.removeClass('is-active');
    }

    if(password === '') {
      $inputPassword.addClass('is-active');
    } else {
      $inputPassword.removeClass('is-active');
    }
  } else {
    const params = {
      email: userName,
      password: password,
      response_type: 'token',
      client_id: loginClientId,
      token: loginToken
    };

    $.ajax({
      method: 'POST',
      url: 'https://account.teambition.com/api/login/email',
      data: params,
      success(data) {
        localStorage.setItem('access_token', data.access_token);
        localStorage.setItem('userName', data.user.name);
        location.href = '/search.html';
      },
      error(data) {
        alert(data.responseJSON.message);
      },
    });
  }
});

